﻿(function(){
	
	com.yogi.core.ContentPanel = function( qs ){
		com.yogi.core.ContentPanel.CATALOGLOADED_EVENT = "CATALOGLOADED_EVENT";
		com.yogi.core.ContentPanel.HYPE_DOC_LOADED_EVENT = "HYPE_DOC_LOADED_EVENT";
		com.yogi.core.ContentPanel.HTML_DOC_LOADED_EVENT = "HTML_DOC_LOADED_EVENT";
		
		com.yogi.core.ContentPanel.html_documents = {};		//key:guid, value: object, with element_ids
		
		com.yogi.core.ContentPanel.MAX_ZINDEX = 10000;
		com.yogi.core.ContentPanel.current_zindex = 0;
		
		var script_loader = $.loadBundleScripts;
		//全局资源管理器
		var resourceBundle = com.yogi.core.ResourceBundle.getInstance();
		
		var query_string_map = qs || $.QueryString;
		//private properties
		var content_panel_div = null;
		var global_config_json = null;
		var runtime_config = {};
		var base_path = "";
		//零件ID查找表,用以判断零件是否已经加载过了
		var flexParts = [];
		////零件查找表,key是ID,value是零件本身
		var flexPartsMap = [];
		//flexPage的集合
		var flexPages = [];
		var home_catalog;
		
		var m_previous_catalog=null;				
		var wrapper_manager = new com.yogi.core.WrapperManager();
		
		//作为加载进度条的零件组(map)，不同的进度条属于不同的负数组，key是ID, value是零件
		var m_loading_icon_part_map = {};
		//当前加载进度条的ID
		var m_current_loading_icon_part = 0;
		var m_loading_icon_part = null;
		var m_current_loading_config;
		
		var m_design_last_selected_part = 0;
		
		function create_content_panel(config){
			config = config || {
					stage_width: $(window).width(),
					stage_height: $(window).height(),
					ct:document.body
			};
			runtime_config = config;
			var width = config.stage_width;
			var height = config.stage_height;			
			var center_div = $("<center></center>");
			center_div.appendTo(config.ct);
			$("<div id=\"ContentPanel\" class=\"trans_png\" style=\"position:relative;overflow:hidden;width:" + width + "px;height:" + height + "px;\"></div>").appendTo(center_div);
			//$("<div id=\"ContentPanel\" class=\"trans_png\" style=\"position:relative;overflow:hidden;width:" + width + "px;\"></div>").appendTo(center_div);
			$("<div id=\"DesignLayer\" style=\"position:relative;overflow:hidden;\"></div>").appendTo(center_div);
			content_panel_div = $("#ContentPanel");
			//Ext.dump(config.ct.html());
		}
		
		function load_HYPE(config){
			base_path = config ? config.base_path : "";
			$.cachedScript(base_path + "lib/HYPE.js?hype_version=100").done( function(data, textStatus) {	
				if(textStatus != "success"){
					throw "lack of HYPE.js";
				}
				load_global_config(config);
			});
		}
		function load_global_config(config) {
			$.getJSON(base_path + "config.txt?_=" + Math.random(),function(global_config,textStatus){				
				if(textStatus != "success") {
					throw "lack of global config info";
				}
				//alert('global config read done: ' + base_path + "config.txt");
				process_global_config(global_config);				
				if(! (config && config.is_console) ) {
					loadContent(query_string_map["target"]);
				}
			});
		}		
		function process_global_config(config){
			global_config_json = config;
			//Ext.dump(global_config_json);			
			wrapper_manager.init(global_config_json.wrapper_definition);
			init_application_style();
			//初始化全局资源管理器
			resourceBundle = com.yogi.core.ResourceBundle.getInstance();
			initVisitStat();
			initHomeCatalog();
		}
		function loadContent(target){
			if(!Ext.isEmpty(target)){
				doLoadCatalog(target);
			} else {
				if(!Ext.isEmpty(global_config_json["frontmovie"])){
					doLoadCatalog(global_config_json["frontmovie"]);
				}else{
					loadHomePage();
				}
			}
		}
		function initHomeCatalog(){
			home_catalog = global_config_json.homepage ||  "homepage";
		}
		function initVisitStat(){
			$(_self).bind(com.yogi.core.ContentPanel.CATALOGLOADED_EVENT, function(e, data) {
				if(global_config_json["visitstat"] == true) {					
					com.yogi.runtime.VisitStat.record(data.current,global_config_json["virDir"]);
				}
			});
		}
		function doLoadCatalog(catalogEname) {
			if(_self.designSite) {
				Ext.dump("load catalog:" + catalogEname);
				return;
			}
			
			var oldPage = flexPages[catalogEname];
			$(_self).trigger(com.yogi.core.ContentPanel.CATALOGLOADED_EVENT, {
					previous: m_previous_catalog,
					current: catalogEname
			});
			m_previous_catalog = catalogEname;
			//要加载的栏目页是否已存在?
			if(!Ext.isEmpty(oldPage)) {
				oldPage.clearWorkTable();
				doCheckScreen(oldPage);
				return { success:true, flow:"doCheckScreen" };
			}else{
				var createRet = createNewPage(catalogEname);
				return { success:createRet, flow:"createNewPage" };
			}
		}
		function  loadHomePage() {
			doLoadCatalog(home_catalog);
		}
		function getDisplayList() {
			return $("#ContentPanel > div");
		}
		function getPartFromDivId(divId) {
			var partId = divId.substr( com.yogi.core.FlexPart.DIV_ID_PREFIX.length );
			//Ext.dump("divId=" + divId + ",partId=" + partId);
			return  flexPartsMap[ partId ];
		}
		/**
		 * 最复杂的流程之一： 
		 * 检查屏幕显示页的每个可视零件(簿记screen_visible_parts)，与要加载页的“页面零件表”比照，得到“需消失的零件表”和“需保留的零件表”这两张表，
		 * 后表添入“页面需显示零件表”,注意排除进度条，进度条要加入ContentPanel容器
		 */
		function doCheckScreen(newPage) {
			var displayList = getDisplayList();
			//Ext.dump(content_panel_div.html());
			//if(console) console.log(content_panel_div.html());
			//if(typeof(console) != "undefined") console.log(displayList.length);
			if(displayList.length > 0) {												//显示列表中有东西
				var newPartsConfig = newPage.getPartsConfig();				
				var need_reserve_parts_config = new Array();			//需要保留的零件表					
				var need_hide_parts_config = new Array();				//需要隐藏的零件表
				$.each(displayList, function(index, div) {
					var oldPart = getPartFromDivId(div.id);
					var oldConfig = oldPart.getConfig();		
					if(oldConfig.LoadGroup >= 0) {					//跳过进度条
						var find = false;
						if(newPartsConfig != null) {
							$.each(newPartsConfig, function(i, newConfig) {								
								if(oldConfig.Id == newConfig.Id) {
									find = true;																						
									need_reserve_parts_config.push(oldConfig.Id);		//需保留	
									return false;
								}
							});
						}
						if(!find){
							//需消失的零件配置记录下来					
							need_hide_parts_config.push(oldConfig);
						}	
					}
				});
				//if(typeof(console) != "undefined") console.log(need_hide_parts_config);
				//if(typeof(console) != "undefined") console.log(need_reserve_parts_config);
				newPage.setReservePartConfig(need_reserve_parts_config);
				if(need_hide_parts_config.length > 0) {
					hideParts(need_hide_parts_config,newPage);
					return need_hide_parts_config;
				}else{
					newPage.loadParts();
				}	
			}else{
				newPage.loadParts();
			}
			return [];
		}		
		function hideParts(need_hide_parts_config,newPage) {
			var flexPartDisplay = new com.yogi.core.FlexPartDisplay(newPage);
			$(flexPartDisplay).bind(com.yogi.core.FlexPartDisplay.EVENT_DONE, onPartsHideDone);
			return flexPartDisplay.showParts(need_hide_parts_config,false);
		}
		/**
		 * 确保零件的消失过程全部完成
		 */
		function onPartsHideDone(e, data) {
			var newPage = data.page;
			newPage.loadParts();
		}
		/**
		 * 加载栏目页分支流程： 全新页面的情况
		 */
		function createNewPage(catalogEname, new_page) {
			var page = new_page || new com.yogi.core.FlexPage();
			flexPages[catalogEname] = page;						
			
			//开始获取页面的配置信息
			var qs_preview = query_string_map["preview"];
			var preview = !Ext.isEmpty(qs_preview);
			return page.load(getLoadCatalogPartsJsonUrl(catalogEname, preview));
		}
		function getLoadCatalogPartsJsonUrl(catalogEname,preview){
			var static_config = global_config_json.static_config == "true";
			if(static_config){
				static_config = !runtime_config.is_console;
			}
			if(preview){
				static_config = false;					//预览，则直接查看动态配置版本
			}
			if(static_config){				
				return base_path + "config/main/" + catalogEname + "/c.txt?_=" + Math.random();
			}else{		
				return global_config_json.virDir + "/plugins/syskernel/yogihtml5action.ashx?cmd=loadcatalogparts&catalogename=" + catalogEname;
			}
		}
		function init_application_style(){
			var backgroundColor = global_config_json.backgroundColor || 0x2c1e00;
			$(document.body).css("backgroundColor",backgroundColor);
		}
		function prepareWrapperCls(partsConfig) {
			var wrapper_container_urls = [];
			var prefix = _self.getVirDir() + "/yogi/wrappers/";
			if(prefix.indexOf("//") == 0) prefix = prefix.substring(1);
			//if(typeof(console) != "undefined")  console.log(prefix);
			var wrapperTypesToLoad = new Array();								//處理要加載的包裝器類，注意複合包裝器的情況可能要加載多個
			$.each(partsConfig, function(index,part_config) {
				if(!Ext.isEmpty(part_config.WrapperParam)) {
					//console.log(part_config.WrapperParam);
					var wrapperDef = $.parseJSON(part_config.WrapperParam);
					stripWrapperTypeFromPartConfig(wrapperDef,wrapperTypesToLoad);
				}	
			});
			$.each(wrapperTypesToLoad, function(index, wrapperType) {
				if(! wrapper_manager.existsWrapperType(wrapperType))	{
					var wrapperClsCt = wrapper_manager.getWrapperCtName(wrapperType);
					if(wrapperClsCt){
						var ct_url = prefix  + wrapperClsCt + ".js";
						if(wrapper_container_urls.indexOf(ct_url) < 0){
							wrapper_container_urls.push(ct_url);
						}	
					}
				}
			});
			return wrapper_container_urls;
		}
		/*
		 * 這裡可能要遞歸，因為存在複合包裝器的情況
		 */
		function stripWrapperTypeFromPartConfig(wrapperDef,wrapperTypesToLoad) {
			var wrapperType = wrapperDef.type;
			if(wrapperType == "composite") {
				var children = wrapperDef.children;
				$.each(children, function(index, child){
					var sub_wrapper_def = child.wrapper;
					stripWrapperTypeFromPartConfig(sub_wrapper_def,wrapperTypesToLoad);
				});
			}
			else
			{
				wrapperTypesToLoad.push(wrapperType);
			}
		}
		/*
		* 從零件定義中加載包裝器類並加入到包裝器管理器中
		*/
		function doLoadWrapperCls(partsConfig,page) {
			var wrapper_container_urls = prepareWrapperCls(partsConfig);
			if(wrapper_container_urls.length == 0) {		//沒有需要加載的包裝器類				
				doCheckScreen(page);
			} else {
				var ct_registered = [];
				var ct_need_load_amount = wrapper_container_urls.length;
				script_loader(wrapper_container_urls, function() {
					//the loaded script execute asynchronously!
					$(wrapper_manager).bind(com.yogi.core.WrapperManager.WRAPPER_TYPE_REGISTERED, function(e,data) {
						var reg_ct = wrapper_manager.getWrapperCtName(data.type);
						if(ct_registered.indexOf(reg_ct) < 0){
							ct_registered.push(reg_ct);
						}
						if(ct_registered.length == ct_need_load_amount)
						{
							$(wrapper_manager).unbind(com.yogi.core.WrapperManager.WRAPPER_TYPE_REGISTERED);
							doCheckScreen(page);
						}
					});										
				}, _self);
			}
		}
		/**
		 * 清空除了需保留零件以外的其他零件
		 */
		function doClearScreen(newPage) {
			var displayList = getDisplayList();
			//Ext.dump("doClearScreen");
			$.each(displayList, function(index, div) {
				var part = getPartFromDivId(div.id);	
				var partId = part.getConfig().Id;
				//if(typeof(console) != "undefined")  console.log(partId);
				if(part != null && !newPage.isPartReserved(partId)){
					if(_self.designSite){
						$(div).remove();
					}else{
						$(div).hide();
					}
				}
			});
		}
		function doLoadResources(resUrls,callback,scope){
			adjustLoadingIcon();	
			//console.log(resUrls);
			resourceBundle.loadResources(resUrls,callback,scope);
		}
		function doGetResourceDirect(resUrl) {
			return resourceBundle.getResourceDirect(resUrl);
		}
		function get_loading_icon_part() {
			return m_loading_icon_part_map[m_current_loading_icon_part];
		}
		/**
		 * 调整进度条的位置到顶层
		 */
		function adjustLoadingIcon() {
			//调整进度条的位置
			var loading_icon_part = get_loading_icon_part();
			if(loading_icon_part != null && contains(loading_icon_part)){				
				var partDIV = loading_icon_part.getDIV();
				partDIV.show();
				partDIV.css("zIndex", com.yogi.core.ContentPanel.MAX_ZINDEX);
				loading_icon_part.show(true);
			}
		}
		function doHideLoadingIcon(){
			var loading_icon_part = get_loading_icon_part();
			if(loading_icon_part != null && contains(loading_icon_part)){
				var partDIV = loading_icon_part.getDIV();
				partDIV.hide();

				if($("#preload_ph") && getDisplayList().length > 1){
					$("#preload_ph").remove();
				}
			}
		}
		function contains(part) {
			return flexParts.indexOf(part.getConfig().Id) >= 0;
		}
		function doRecordPart(part) {
			var partConfig = part.getConfig();
			var part_id = partConfig.Id;
			flexParts.push(part_id);
			flexPartsMap[part_id] = part;
			if(partConfig.LoadGroup < 0 ){							//这是进度条!
				m_current_loading_config = partConfig;
				m_current_loading_icon_part = part_id;
				if(m_loading_icon_part == null) {
					//同一个ID的Loading只加载一次
					m_loading_icon_part_map[part_id] = part;		//记录下来
					var partDIV = part.getDIV();
					//$("<div>loading...</div>").appendTo(partDIV);
					partDIV.appendTo(content_panel_div);						
					part.resetDisplayParam();
					m_loading_icon_part = part;
					partDIV.show(true);
				} 
				adjustLoadingIcon();	
			}
		}
		/**
		 * 依次加载零件
		 */
		function doAttachParts(page,clearScreen) {
			//alert(clearScreen);
			if( clearScreen) {
				var dl = getDisplayList();
				$.each(dl,function(i, div){
					if(_self.designSite){
						$(div).remove();
					}else{
						$(div).hide();
					}
				});
			}
			//if(console)console.log("doAttachParts:" + content_panel_div.html());
			var partsConfig = page.getPartsConfig();
			//依次加载零件，注意页面的"保留列表"的零件不用调用show
			$.each(partsConfig, function(idx, config){
				if(config.LoadGroup >= 0){
					var part = flexPartsMap[config.Id];
					if(part != null){		//有可能是空的！		
						var partDIV = part.getDIV();	
						if(!page.isPartReserved(part.getConfig().Id)){							
							partDIV.appendTo(content_panel_div);
							//partDIV.css("zIndex", com.yogi.core.ContentPanel.current_zindex++);
						}
						partDIV.css("zIndex", idx);
						part.show(true);
					}
				}
			});
			//Ext.dump(content_panel_div.html());
		}
		function doLoadDesignPage(pageId,parts_config) {			
			content_panel_div.css("overflow","visible");
			flexParts = [];		//clear it
			var page = new com.yogi.core.FlexPage();
			if(m_design_last_selected_part > 0){
				var part = flexPartsMap[m_design_last_selected_part];
				if(part != null){		//有可能是空的！
					part.highLight(true);
				}
			}
			doClearScreen(page);
			page.loadDesignParts(pageId,parts_config);
		}
		function doHighLightDesignPart(partId) {
			if(m_design_last_selected_part > 0){
				var last_selected_part = flexPartsMap[m_design_last_selected_part];
				last_selected_part.highLight(true);
			}
			var part = flexPartsMap[partId];
			if(part != null){		//有可能是空的！
				part.highLight();
				m_design_last_selected_part = partId;
			}	
		}
		function doLoadPartStructureInfo(partId) {
			var result = [];			
			var part = flexPartsMap[partId];
			if(part != null) {	 
				var hype_doc = part.getHypeDoc();
				if(hype_doc) {
					var elements_map = hype_doc.elements_map;
					for(var show_name in elements_map) {
						result.push(show_name);
					}					
				} else {
					var html_doc = part.getHtmlDoc();
					if(html_doc) {
						result = html_doc.elements;
					}
				}
			}
			return result;
		}
		//contentpanel interface
		var _self = {
			objType:"ContentPanel interface",
			designSite: null,
			init : function(config) {
				create_content_panel(config);			
				load_HYPE(config);	
			},
			hideLoadingIcon: function(){
				//if(typeof(console) != "undefined")  console.log("hideLoadingIcon");
				doHideLoadingIcon();
			},
			getVirDir: function() {
				var virDir = global_config_json["virDir"];
				if(!Ext.isEmpty(virDir)){
					if(virDir[0] != "/") virDir = "/" + virDir;
				}else{
					virDir = "/";
				}
				return virDir;
			},
			loadCatalog: function(catalogEname){
				return doLoadCatalog(catalogEname);
			},
			loadHomePage: function(){
				return loadHomePage();
			},
			loadDesignPage: function(pageId, parts_config ) {
				return doLoadDesignPage(pageId,parts_config);
			},
			highLightDesignPart: function(partId) {
				doHighLightDesignPart(partId);
			},
			loadPartStructureInfo: function(partId) {
				return doLoadPartStructureInfo(partId);
			},
			clearScreen: function(page){
				doClearScreen(page);
			},
			checkScreen: function(page) {
				return doCheckScreen(page);
			},
			get_content_panel:function() {
				return content_panel_div;
			},
			get_loading_indicate_image:function() {
				return m_loading_icon_part.getDIV().find("img").attr("src");
			},
			loadResources: function(resUrls,callback,scope) {
				return doLoadResources(resUrls,callback,scope);
			},
			getResourceDirect: function(resUrl) {
				return doGetResourceDirect(resUrl);
			},
			getWrapperManager: function(){
				return wrapper_manager;
			},
			loadWrapperCls: function(partsConfig,page){
				return doLoadWrapperCls( partsConfig,page );
			},
			get_global_config:function(){
				return global_config_json;
			},
			//检查每个零件是否已经在零件ID查找表存在
			isPartLoaded: function (partId) {
				return flexParts.indexOf(partId) >= 0;
			},
			getPart: function(partId){
				return flexPartsMap[partId];
			},
			//已加载到页面的零件簿记，注意，零件中的资源现在未必已加载进来
			recordPart: function(part) {
				doRecordPart(part);				
			},
			attachParts: function(page,clearScreen) {
				doAttachParts(page,clearScreen);
			},
			test_func: function(func_name, args){
				eval("var inner_func = " + func_name);
				if($.isFunction(inner_func)){
					return inner_func.apply(this, args);
				}
				return inner_func;
			},
			test_setter: function(lh,rh) {
				var stmt = lh + "=" + rh + ";";
				eval(stmt);
			}
		} ;
		return _self;
	};
	function dummy(){
		new com.yogi.core.ContentPanel();
	}
	$(window).trigger(com.yogi.core.EVENT_EXTERNAL_SCRIPT_LOADED,  { script:"com.yogi.core.ContentPanel" });
})();	